<template>
	<view class="activity">
		<!-- 卡路里 -->
		<view class="card calories noDay">
			<view class="head">
				<image class="w-92rpx" src="@/static/ring/chart/Calories.png" mode="widthFix"></image>
				<view class="title">卡路里</view>
				<uni-icons type="info-filled" class="ml-10rpx" size="20" color="#666666" @click="openTip('calories')"></uni-icons>
				<view class="value">{{ calories.averageNum }}<text>KCAL</text></view>
			</view>
			<view class="chart">
				<view v-if="caloriesNotDataOrLoading" class="noData_loading_mask">
					{{ !calories.loading ? "暂无数据" : "加载中..." }}
				</view>
				<l-echart ref="calChartRef"></l-echart>
			</view>
		</view>
		<view class="info" v-if="calories.healthText && calories.averageNum">
			<view class="info-content">
				<text>{{ calories.healthText }}</text>
			</view>
		</view>

		<!-- 步数 -->
		<view class="card steps noDay">
			<view class="head">
				<image class="w-92rpx" src="@/static/ring/chart/step.png" mode="widthFix"></image>
				<view class="title">步数</view>
				<uni-icons type="info-filled" class="ml-10rpx" size="20" color="#666666" @click="openTip('steps')"></uni-icons>
				<view class="value">{{ steps.averageNum }}</view>
			</view>
			<view class="chart">
				<view v-if="stepsNotDataOrLoading" class="noData_loading_mask">
					{{ !steps.loading ? "暂无数据" : "加载中..." }}
				</view>
				<l-echart ref="stepChartRef"></l-echart>
			</view>
		</view>
		<view class="info" v-if="steps.healthText && steps.averageNum">
			<view class="info-content">
				<text>{{ steps.healthText }}</text>
			</view>
		</view>

		<!-- 距离 -->
		<view class="card distance noDay">
			<view class="head">
				<image class="w-92rpx" src="@/static/ring/chart/distance.png" mode="widthFix"></image>
				<view class="title">距离</view>
				<uni-icons type="info-filled" class="ml-10rpx" size="20" color="#666666" @click="openTip('distance')"></uni-icons>
				<view class="value">{{ distance.averageNum }}<text>km</text></view>
			</view>
			<view class="chart">
				<view v-if="distanceNotDataOrLoading" class="noData_loading_mask">
					{{ !distance.loading ? "暂无数据" : "加载中..." }}
				</view>
				<l-echart ref="disChartRef"></l-echart>
			</view>
		</view>
		<view class="info" v-if="distance.healthText && distance.averageNum">
			<view class="info-content">
				<text>{{ distance.healthText }}</text>
			</view>
		</view>
	</view>
</template>
<script>
import dayjs from "dayjs";
import * as echarts from "echarts";

import cImage from "@/static/ring/chart/Calories.png";
import sImage from "@/static/ring/chart/step.png";
import dImage from "@/static/ring/chart/distance.png";

import { queryMyStepInfoByDay, queryMyStepInfoByWeek, queryMyStepInfoByMonth } from "@/api/ring/chart.js";

const tip_zh = `
卡路里消耗显示用户在一天内通过活动燃烧的能量。

该指标结合用户的体重、身高、年龄和活动类型计算，帮助用户了解每日能量消耗情况。

通过监测卡路里消耗，用户可以更好地管理体重和健康状况，确保能量平衡。

注：本设备提供的检测数据仅用于日常健康管理辅助参考，不可替代专业医疗诊断。
`;

const tip_zh2 = `
步数记录用户每日的行走步数，通过内置传感器精确计算。

步数不仅是衡量身体活动量的简单指标，还能帮助用户设定并实现健康目标。

日常行走有助于提高心血管健康、增强肌肉力量和促进新陈代谢。

*年轻人：最佳步数范围在8000-10000步之间。

*60岁以上老年人：最佳步数范围在6000-8000步之间。

达到这些步数目标，有助于维持和改善整体健康状况。
`;

const tip_zh3 = `
行走距离通过步数和步幅计算得出，表示用户每日行走的总距离。

该指标有助于用户了解行走或跑步的总里程，定期行走一定距离对心脏健康、骨骼强度和整体体能都有显著益处。
`;

const _options = () => {
	return {
		color: ["#E5404F"],
		grid: {
			left: "0",
			right: "15",
			top: "10",
			bottom: "2",
			containLabel: true,
		},
		xAxis: [
			{
				show: true,
				type: "category",
				boundaryGap: false,
				axisTick: {
					show: false,
				},
				axisLine: {
					//坐标轴轴线相关设置。数学上的x轴
					show: true,
					lineStyle: {
						color: "rgba(141, 141, 141, 0.3)",
					},
				},
				axisLabel: {
					//坐标轴刻度标签的相关设置
					textStyle: {
						color: "rgba(0, 0, 0, 0.5)",
					},
				},
			},
		],
		yAxis: [
			{
				type: "value",
				min: 0,
				splitLine: {
					show: true,
					lineStyle: {
						type: "dashed",
						color: "rgba(141, 141, 141, 0.3)",
					},
				},
				axisLabel: {
					//坐标轴刻度标签的相关设置
					textStyle: {
						color: "rgba(0, 0, 0, 0.5)",
					},
				},
			},
		],
	};
};

const _calOptions = _options();
const _stepOptions = _options();
const _distanceOptions = _options();

export default {
	props: {
		selectDateInfo: Object,
	},
	data() {
		return {
			selectType: "day",
			calories: {
				type: "calories",
				showTip: false,
				tipText: tip_zh,
				max: 0,
				min: 0,
				averageNum: 0,
				chartData: [],
				chartRef: null,
				chart: null,
				healthText: "",
				healthModelValue: 0,
				loading: false,
				empty: false,
			},
			steps: {
				type: "steps",
				showTip2: false,
				tipText2: tip_zh2,
				max: 0,
				min: 0,
				averageNum: 0,
				chartData: [],
				chartRef: null,
				chart: null,
				healthText: "",
				healthModelValue: 0,
				loading: false,
				empty: false,
			},
			distance: {
				type: "distance",
				showTip2: false,
				tipText2: tip_zh3,
				max: 0,
				min: 0,
				averageNum: 0,
				chartData: [],
				chartRef: null,
				chart: null,
				healthText: "",
				healthModelValue: 0,
				loading: false,
				empty: false,
			},
			showTip: false,
			tip: tip_zh,
			icon: "@/static/ring/chart/Calories.png",
			title: "卡路里",
		};
	},

	computed: {
		caloriesNotDataOrLoading() {
			const data = this.calories.chartData;
			return !data || !Array.isArray(data) || !data.length;
		},
		stepsNotDataOrLoading() {
			const data = this.steps.chartData;
			return !data || !Array.isArray(data) || !data.length;
		},
		distanceNotDataOrLoading() {
			const data = this.distance.chartData;
			console.log('distance data', data);
			return !data || !Array.isArray(data) || !data.length;
		},
		optionsCalDay() {
			return {
				..._calOptions,
				series: [
					{
						name: "Line 1",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						showSymbol: true,
						symbolSize: 1.5,
						symbol: "circle",
						itemStyle: {
							color: "#BF3541",
						},
						areaStyle: {
							opacity: 1,
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{
									offset: 0,
									color: "#BF3541",
								},
								{
									offset: 1,
									color: "rgba(191, 53, 65, 0)",
								},
							]),
						},
						data: this.calories.chartData,
					},
				],
			};
		},
		optionsCalOther() {
			return {
				..._calOptions,
				series: [
					{
						name: "Line 1",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						areaStyle: {
							opacity: 0,
						},
						showSymbol: true,
						symbol: "circle",
						data: this.calories.chartData,
					},
				],
			};
		},
		optionsStepDay() {
			return {
				..._stepOptions,
				series: [
					{
						name: "步数",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						showSymbol: true,
						symbolSize: 1.5,
						symbol: "circle",
						itemStyle: {
							color: "#BF3541",
						},
						areaStyle: {
							opacity: 1,
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{
									offset: 0,
									color: "#BF3541",
								},
								{
									offset: 1,
									color: "rgba(191, 53, 65, 0)",
								},
							]),
						},
						data: this.steps.chartData,
					},
				],
			};
		},
		optionsStepOther() {
			return {
				..._stepOptions,
				series: [
					{
						name: "Line 1",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						areaStyle: {
							opacity: 0,
						},
						showSymbol: true,
						symbol: "circle",
						data: this.steps.chartData,
					},
				],
			};
		},
		optionsDisDay() {
			return {
				..._distanceOptions,
				series: [
					{
						name: "距离",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						showSymbol: true,
						symbolSize: 1.5,
						symbol: "circle",
						itemStyle: {
							color: "#BF3541",
						},
						areaStyle: {
							opacity: 1,
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{
									offset: 0,
									color: "#BF3541",
								},
								{
									offset: 1,
									color: "rgba(191, 53, 65, 0)",
								},
							]),
						},
						data: this.distance.chartData,
					},
				],
			};
		},
		optionsDisOther() {
			return {
				..._distanceOptions,
				series: [
					{
						name: "距离",
						type: "line",
						smooth: false,
						lineStyle: {
							width: 1.5,
							color: "#E5404F",
						},
						areaStyle: {
							opacity: 0,
						},
						showSymbol: true,
						symbol: "circle",
						data: this.distance.chartData,
					},
				],
			};
		},
	},

	watch: {
		selectDateInfo: {
			handler(nv) {
				this.selectType = nv.type;
				this.allOnChange(nv);
			},
			deep: true,
		},

		optionsCalDay: {
			handler(nv) {
				console.log("optionsCalDay");

				if (this.selectType === "day") {
					if (this.calories.chart) {
						setTimeout(() => {
							this.calories.chart.setOption(nv);
						}, 0);
					}
				}
			},
			deep: true,
		},
		optionsCalOther: {
			handler(nv) {
				if (this.selectType !== "day") {
					setTimeout(() => {
						this.calories.chart.setOption(nv);
					}, 0);
				}
			},
			deep: true,
		},
		optionsStepDay: {
			handler(nv) {
				console.log("optionsStepDay");

				if (this.selectType === "day") {
					if (this.steps.chart) {
						this.steps.chart.setOption(nv);
					}
				}
			},
			deep: true,
		},
		optionsStepOther: {
			handler(nv) {
				if (this.selectType !== "day") {
					if (this.steps.chart) {
						setTimeout(() => {
							this.steps.chart.setOption(nv);
						}, 500);
					}
				}
			},
			deep: true,
		},

		optionsDisDay: {
			handler(nv) {
				console.log("optionsDisDay");

				if (this.selectType === "day") {
					if (this.distance.chart) {
						setTimeout(() => {
							this.distance.chart.setOption(nv);
						}, 1500);
					}
				}
			},
			deep: true,
		},
		optionsDisOther: {
			handler(nv) {
				if (this.selectType !== "day") {
					if (this.distance.chart) {
						setTimeout(() => {
							this.distance.chart.setOption(nv);
						}, 1500);
					}
				}
			},
			deep: true,
		},
	},
	async mounted() {
		// 卡路里
		if (!this.calories.chartRef) {
			this.calories.chartRef = this.$refs.calChartRef;
		}
		if (this.calories.chartRef) {
			this.calories.chart = await this.calories.chartRef.init(echarts);
		}

		// 步数
		if (!this.steps.chartRef) {
			this.steps.chartRef = this.$refs.stepChartRef;
		}
		if (this.steps.chartRef) {
			this.steps.chart = await this.steps.chartRef.init(echarts);
		}

		// 距离
		if (!this.distance.chartRef) {
			this.distance.chartRef = this.$refs.disChartRef;
		}
		if (this.distance.chartRef) {
			this.distance.chart = await this.distance.chartRef.init(echarts);
		}
	},

	methods: {
		async allOnChange(data) {
			console.log("allOnChange", data);

			const { type, startTime, endTime } = data;
			this.calories.max = 0;
			this.calories.min = 0;
			this.calories.averageNum = 0;
			this.calories.healthText = "";
			this.calories.healthModelValue = 0;
			this.calories.chartData = [];
			this.calories.loading = true;
			this.resetData();

			const offsetMinutes = new Date().getTimezoneOffset();

			const params =
				type == "day"
					? { dateStr: startTime, offsetMinutes }
					: type === "week"
					? { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes }
					: { dateBeginStr: startTime, dateEndStr: endTime, offsetMinutes };
			console.log("params", params);

			const requestMethod = type == "day" ? queryMyStepInfoByDay : type == "week" ? queryMyStepInfoByWeek : queryMyStepInfoByMonth;

			try {
				const { data } = await requestMethod(params);
				console.log("data", data);

				if (!data) {
					this.resetData();
					return;
				}

				const dealWith = type == "day" ? this.dataGetFullByDay : this.dataGetFullByOther;

				// 卡路里
				setTimeout(() => {
					this.calories.loading = false;
					this.calories.averageNum = data.calSum ? Number(data.calSum).toFixed(1) : 0;
					this.calories.healthText = data?.calModel?.config?.modelZh;
					this.calories.healthModelValue = parseInt(data?.calModel?.value || 0);
					if (this.calories.chart) {
						console.log("清理 calories");
						this.calories.chart.clear();
					}
					if (data.calRates) {
						dealWith("calories", data.calRates || []);
					}
				}, 1000);

				// 步数
				setTimeout(() => {
					this.steps.loading = false;
					this.steps.averageNum = parseInt(data.sum || 0);
					this.steps.healthText = data?.stepModel?.config?.modelZh;
					this.steps.healthModelValue = parseInt(data?.stepModel?.value || 0);
					if (this.steps.chart) {
						console.log("清理 steps");
						this.steps.chart.clear();
					}
					if (data.rates) {
						dealWith("steps", data.rates || []);
					}
				}, 2000);

				// 距离
				setTimeout(() => {
					this.distance.loading = false;
					this.distance.averageNum = data.distanceSum ? Number(data.distanceSum).toFixed(1) : 0;
					this.distance.healthText = data?.disModel?.config?.modelZh;
					this.distance.healthModelValue = parseInt(data?.disModel?.value || 0);
					if (this.distance.chart) {
						console.log("清理 distance");
						this.distance.chart.clear();
					}
					if (data.distanceRates) {
						console.log("distanceRates", data.distanceRates);
						dealWith("distance", data.distanceRates || []);
					}
				}, 3000);
			} catch (error) {
				console.log("allOnChange error", error);
				this.resetData();
			}
		},

		async resetData() {
			this.calories.chartData = [];
			this.calories.averageNum = 0;
			this.steps.chartData = [];
			this.steps.averageNum = 0;
			this.distance.chartData = [];
			this.distance.averageNum = 0;
		},

		dataGetFullByDay(type, rates) {
			let res = [];
			// if (rates.every((item) => item.value < 1)) return;
			for (let i = 0; i < 24; i++) {
				const has = rates.findIndex((item) => Number(item.time) === i);
				if (has != -1) {
					res.push([i.toString() + ":00", rates[i].value || null]);
				} else {
					res.push([i.toString() + ":00", null]);
				}
			}
			res.sort((a, b) => Number(a[0]) - Number(b[0]));

			this[type].chartData = res;
			console.log(type, "res", this[type].type, this[type].chartData);
		},

		dataGetFullByOther(type, data) {
			const cycleCount = this.selectType == "week" ? 7 : data.length;
			let res = [];
			if (data.every((item) => item.value < 1)) return (chartCData.value = []);
			for (let i = 0; i < cycleCount; i++) {
				res.push([dayjs(data[i].date).format("MM.DD"), data[i].value || null]);
			}
			this[type].chartData = res;
		},

		openTip(type) {
			const tips = {
				tip: tip_zh,
				icon: cImage,
				title: "卡路里",
			};
			switch (type) {
				case "calories":
					tips.tip = tip_zh;
					tips.icon = cImage;
					tips.title = "卡路里";
					break;
				case "steps":
					tips.tip = tip_zh2;
					tips.icon = sImage;
					tips.title = "步数";
					break;
				case "distance":
					tips.tip = tip_zh3;
					tips.icon = dImage;
					tips.title = "距离";
					break;

				default:
					tips.tip = tip_zh;
					tips.icon = cImage;
					tips.title = "卡路里";
					break;
			}

			this.$emit("tips", tips);
		},
	},
};
</script>
<style lang="scss" scoped>
.activity {
	width: 100%;
	height: max-content;

	.w-92rpx {
		width: 92rpx;
	}

	.w-60rpx {
		width: 60rpx;
	}

	.w-70rpx {
		width: 70rpx;
	}

	.w-40rpx {
		width: 40rpx;
	}

	.w-30rpx {
		width: 30rpx;
	}

	.mr-8rpx {
		margin-right: 8rpx;
	}

	.text-#AFAFAF {
		color: #afafaf;
	}

	.card {
		width: 100%;

		background-color: rgba($color: white, $alpha: 0.5);
		backdrop-filter: blur(20rpx);
		border-radius: 50rpx;
		height: 630rpx;

		padding: 40rpx;

		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.head {
			width: 100%;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				text-align: left;
				margin-left: 6cap;
				margin-right: 12rpx;
			}

			.value {
				margin-left: auto;
				font-weight: 500;
				font-size: 64rpx;

				text {
					font-size: 24rpx;
				}
			}
		}

		.chart {
			width: 100%;
			height: 400rpx;
			position: relative;

			.noData_loading_mask {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				background-color: #e3f1fb;
				display: flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				line-height: 150px;
				font-size: 28rpx;
				color: rgba(45, 153, 255, 1);
			}
			// background-color: #e5404f;
		}

		.range {
			display: flex;
			padding: 20rpx 52rpx 0 40rpx;
			font-weight: 500;

			.des {
				flex: 1;
				color: black;
				font-size: 32rpx;

				.desTop {
					display: flex;
					align-items: center;
					margin-bottom: 4rpx;
					white-space: nowrap;

					.titleTime {
						font-size: 28rpx;
						color: black;
						margin-left: 20rpx;
					}

					.dot {
						background: #e5404f;
						border-radius: 50%;
						width: 10rpx;
						height: 10rpx;
					}
				}

				.value {
					padding-left: 30rpx;

					.unit {
						font-size: 24rpx;
						margin-left: 8rpx;
					}
				}
			}
		}

		& + .card {
			margin-top: 40rpx;
			// height: 730rpx;
		}

		// &.noDay.calories {
		// 	height: 630rpx;
		// }

		// &.noDay.steps {
		// 	height: 630rpx;
		// }

		// &.noDay.distance {
		//     height: 630rpx;
		// }
	}

	.info {
		color: black;
		padding: 40rpx;

		.info-content {
			font-family: PingFang SC;
			font-size: 28rpx;
			font-weight: 300;
			line-height: 40rpx;
			text-align: left;
		}

		margin-bottom: 40rpx;
	}

}
</style>
